from typing import Sequence

import msgspec
from litestar import Controller, get, post, put
from litestar.status_codes import HTTP_200_OK
from sqlalchemy.ext.asyncio import AsyncSession

from model.todo_item import TodoItem
from schema.todo_item import AddTodoItemForm, TodoItemDTO
from service.todo_item import get_todo_by_title, get_todo_list
from util.response import JsonResponse


class TodoItemController(Controller):
    path = "/todo"
    tags = ["todo"]

    @get("", return_dto=TodoItemDTO)
    async def get_todo_items(
        self,
        transaction: AsyncSession,
        done: bool | None = None,
    ) -> JsonResponse[Sequence[TodoItem]]:
        todo_list = await get_todo_list(done, transaction)
        # todo_item_list = [
        #     TodoItem(title=todo.title, done=todo.done) for todo in todo_list
        # ]
        return JsonResponse(msg="OK", code=HTTP_200_OK, data=todo_list)

    @post("", return_dto=TodoItemDTO)
    async def add_toto_item(
        self,
        data: AddTodoItemForm,
        transaction: AsyncSession,
    ) -> JsonResponse[TodoItem]:
        obj = TodoItem(**msgspec.structs.asdict(data))
        transaction.add(obj)
        return JsonResponse(msg="OK", code=HTTP_200_OK, data=obj)

    @put("", return_dto=TodoItemDTO)
    async def update_todo_item(
        self, data: TodoItem, transaction: AsyncSession
    ) -> JsonResponse[TodoItem]:
        todo_item = await get_todo_by_title(data.title, transaction)
        todo_item.title = data.title
        todo_item.done = data.done
        return JsonResponse(msg="OK", code=HTTP_200_OK, data=todo_item)
